package cn.trs.common.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @version 1.0
 * @author:TRS
 * @create:2023/2/23 9:54
 * @description:
 * @ClassName: SnowflakeUtil
 * @company TRS
 */
@Component
public class SnowflakeUtil {

    private static Logger logger = LoggerFactory.getLogger(SnowflakeUtil.class);

    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private static long workerId = 0;//为终端ID
    private long datacenterId = 1;//数据中心ID
    private Snowflake snowflake = IdUtil.createSnowflake(workerId,datacenterId);


    static {
        workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
        logger.info("当前机器的workId:{}",workerId);
        if (ObjectUtil.isNotNull(workerId)){
            workerId = workerId % 32;
        }else{
            workerId = 1l;
        }
        logger.info("[IPUtil] 静态代码块执行，生成workId：{}",workerId);
    }
    public synchronized long snowflakeId(){
        return snowflake.nextId();
    }
    public synchronized long snowflakeId(long workerId,long datacenterId){
        Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
        return snowflake.nextId();
    }
    public synchronized String snowflakeString(){
        return Base62Converter.toBase62(snowflake.nextId());
    }
}
